package pers.ljf.escloud.controller.app.websocket;

import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import pers.ljf.escloud.dto.SocketText;
import pers.ljf.escloud.service.modules.app.UserService;
import pers.ljf.escloud.util.WsSessionManager;

import javax.annotation.Resource;

@Slf4j
@Component
public class WebSocketHandler extends TextWebSocketHandler {
    @Resource
    private UserService userService;

    /**
     * socket 建立成功事件
     *
     * @param session
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        log.info("建立连接，sessionId:{}",session.getId());
    }

    /**
     * 接收消息事件
     *
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 获得客户端传来的消息
        String payload = message.getPayload();
        SocketText socketText = new Gson().fromJson(payload, SocketText.class);
        String token = socketText.getToken();
        userService.validateUserToken(token);
        if (socketText.getMsg() == null) {
            log.info("收到客户端socket，token为:{}",token);
            session.getAttributes().put("token", token);
            WsSessionManager.add(token,session);
            return;
        }
        log.info("收到msg：{}",socketText.getMsg());
    }

    /**
     * socket 断开连接时
     *
     * @param session
     * @param status
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        Object token = session.getAttributes().get("token");
        if (token != null) {
            // 用户退出，移除缓存
            WsSessionManager.remove(token.toString());
        }
    }
}
